package wxdb.index.btree;

import static java.sql.Types.INTEGER;
import wxdb.record.TableInfo;
import wxdb.storage.Page;
import wxdb.tx.PageFormatter;
import wxdb.tx.Transaction;
import wxdb.ui.Global;

public class BTreePageFormatter implements PageFormatter{
	
	private TableInfo ti;
	private int flag;
	
	public BTreePageFormatter(TableInfo ti, int flag){
		this.ti = ti;
		this.flag = flag;
	}
	
	public void format(Page pg){
		Transaction.setInt(ti.getDbid(), pg.getPageID(), 0, flag);
		Transaction.setInt(ti.getDbid(), pg.getPageID(), Transaction.getIntSize(), 0);
		int recordLen = ti.getRecordLen();
		for(int pos=2*Transaction.getIntSize(); pos+recordLen<=Global.STORAGE_PAGE_SIZE;pos+=recordLen)
			makeDefaultRecord(pg, pos);
	}
	
	private void makeDefaultRecord(Page page, int pos) {
	      for (String fldName : ti.getSchema().getFields()) {
	         int offset = ti.getOffset(fldName);
	         int ival;
	         if(fldName.equals("dataval"))
	        	 ival = Integer.MIN_VALUE;
	         else
	        	 ival = 0;
	         if (ti.getSchema().getType(fldName) == INTEGER)
	        	 Transaction.setInt(ti.getDbid(), page.getPageID(), pos+offset, ival);
	         else
	        	 Transaction.setString(ti.getDbid(), page.getPageID(), pos+offset, 
	        			 								"", "".length());
	      }
	}
}
